package sort.heapSort;

/**
 * @Author: zhang
 * @Description:
 * @Date: Created in 18:47 2019/10/5
 */
public class Test {
    public static void main(String[] args) {
        int[] arrays = new int[]{5, 1, 7, 4, 8, 9, 2, 3, 6, 0};
        heapSort(arrays);
        for (int i = 0; i < arrays.length; i++) {
            System.out.print(arrays[i] + " ");
        }
    }

    public static void heapSort(int[] a) {
        for (int i = a.length - 1; i >= 0; i--) {
            adjust(a, i, a.length - 1);
        }

        for (int j = 0; j < a.length - 1; j++) {
            int tmp = a[a.length-1-j];
            a[a.length-1-j] = a[0];
            a[0] = tmp;
            adjust(a,0,a.length-1-j-1);
        }
    }

    public static void adjust(int[] a, int start, int end) {
        int tmp = a[start];
        for (int i = 2 * start + 1; i <= end; i = i * 2 + 1) {
            if (i < end && a[i] < a[i + 1]) {
                i++;
            }
            if (a[i] > tmp) {
                a[start] = a[i];
                start = i;
            } else {
                //a[start] = tmp;
                break;
            }
            a[start] = tmp;
        }
    }
}
